#include "reactor_threadpool.hpp"
#include "login_user_name.hpp"
#include "login_ciphertext.hpp"
#include "tlv_type.h"
#include "packet.h"
#include <iostream>
#include <functional>

using std::cout;
using std::endl;

namespace rocket 
{

reactor_threadpool::reactor_threadpool(int port,string ip,int pool_capacity,int task_list_capacity)
:_server(port,ip)
,_pool(pool_capacity,task_list_capacity)
{

}

reactor_threadpool::~reactor_threadpool()
{

}

void reactor_threadpool::start()
{
    using namespace std::placeholders;
    
    set_callback(std::bind(&reactor_threadpool::new_link,this,_1),
    std::bind(&reactor_threadpool::old_link,this,_1),
    std::bind(&reactor_threadpool::close_link,this,_1));
    _pool.start();
    
    _server.turn_on();

}

void reactor_threadpool::stop()
{
    _server.turn_off();
    _pool.stop();
}

void reactor_threadpool::set_callback(function<void(shared_ptr<tcp_link>)>callback_new,
            function<void(shared_ptr<tcp_link>)>callback_old,
            function<void(shared_ptr<tcp_link>)>callback_close)
{
    _server.set_callback(callback_new,callback_old,callback_close);
}

//处理已经新建立的链接的业务
void reactor_threadpool::new_link(shared_ptr<tcp_link>new_one)
{
    cout<<"new_link "<<new_one->get_link_line()<<endl;
}

//处理已经建立的链接的业务
void reactor_threadpool::old_link(shared_ptr<tcp_link>old_one)
{
    packet data;
    int ret=old_one->read_packet(data);
    //打印接收到的数据
    cout<<"receive data= ";
    data.print();
    //判断数据报文类型
    if (data.get_type() == rocket::LOGIN_USER) 
    //是登录发送用户名报文
    {
        login_user_name task(old_one,data);
        function<void()>f=std::bind(&login_user_name::something,task);
        _pool.add_task(f);

    }
    else if (data.get_type() == rocket::LOGIN_CIPHERTEXT)
    //是登录发送密文报文
    {
        login_ciphertext task(old_one,data);
        function<void()>f=std::bind(&login_ciphertext::something,task);
        _pool.add_task(f);
    }

}   

//处理已经要关闭链接的业务
void reactor_threadpool::close_link(shared_ptr<tcp_link>close_one)
{
    cout<<"close_link "<<close_one->get_link_line()<<endl;
    
}



}//end of namespace rocket
